package com.apps.MobileSms.Aliyun.aspect.impl;

import com.apps.MobileSms.Aliyun.aspect.SendSms;
import com.apps.MobileSms.Aliyun.helper.SendSmsHelper;
import com.apps.MobileSms.Aliyun.model.vo.SmsTemplateVO;
import com.apps.sannotation.constraints.Mobile;
import com.apps.sexctption.DataException;
import com.apps.sexctption.NullException;
import com.apps.shelper.ValidationHepler;
import com.apps.sutils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

/**
 * sendSms注解的实现
 */
@Aspect
@Component
public class SendSmsAspect {

    @Autowired
    private SendSmsHelper sendSmsHelper;


    @Pointcut("@annotation(com.app.thirdparty.sms.aspect.SendSms)")
    public void pointcut() {

    }

    /**
     * 方法执行完之后执行 发送短信业务,从而跟别的注解避开
     * @param joinPoint
     */
    @After("pointcut()")
    public void doAfter(JoinPoint joinPoint) {
        SmsTemplateVO smsTemplate=new SmsTemplateVO();
        Object[] objects=joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SendSms sendSms = signature.getMethod().getAnnotation(SendSms.class);
        Method method = signature.getMethod();
        Parameter[] parameter=method.getParameters();
        Map<String,String> map=new HashMap<>();
        for(int i=0;i<parameter.length;i++){
            String parameterName=signature.getParameterNames()[i];
            if(!objects[i].getClass().isAssignableFrom(String.class))
                throw new DataException("发送短信的传参必须时字符串类型");
            //非空验证
            if(StringUtils.isEmpty(objects[i].toString()))
                throw new NullException("传参不能为空");
            //手机号验证
            Mobile mobile=parameter[i].getAnnotation(Mobile.class);
            if(null!=mobile) {
                ValidationHepler.validMobileAnnotation(parameterName, objects[i], mobile);
                smsTemplate.setPhoneNumbers(objects[i].toString());
                continue;
            }
            map.put(parameterName,objects[i].toString());
        }
        //校验下
        if(StringUtils.isEmpty(smsTemplate.getPhoneNumbers()))
            throw new NullException("发送验证码必须传手机号,用@Mobile注解");
        if(StringUtils.isEmpty(sendSms.templateCode().getTemplateCode()))
           throw new NullException("短信模板编号不能为空");
        smsTemplate.setTemplateCode(sendSms.templateCode().getTemplateCode());
        smsTemplate.setTemplateParam(map);
        //发送短信
        sendSmsHelper.SendSms(smsTemplate);
    }
}
